<?php

class Model_Staff
{
    var $sys;
    private $table_name = "M_STAFF";
    
    public function __construct()
    {
        $this->sys = new Model_SiteManage();
    }

    public function insert($data)
    {
        $db = new Model_DB();
        return $db->insert($this->table_name, $data);
    }
    public function update($id, $data)
    {
        $db = new Model_DB();
        return $db->update($id, $this->table_name, $data);
    }
    public function get($id)
    {
        $db = new Model_DB();
        $sql = sprintf("select * from ".$this->table_name." where id = " . $db->escape($id) . " and enabled = 1");
        $db->query($sql);
        return $db->fetch();
    }
    public function getListCount($data)
    {
        $db    = new Model_DB();
        $where = $this->createSearchCondition($data);
        
        if(array_key_exists('site_id', $data))
            $sql = "select id from ".$this->table_name." left join D_STAFF_AUTH ON ".$this->table_name.".id = D_STAFF_AUTH.staff_id";
        else
            $sql = "select count(id) from ".$this->table_name;
        
        $sql .= (!empty($where) ? " where ".implode(' AND ', $where) : "");
        
        if(array_key_exists('site_id', $data))
        {
            $sql .= ' group by id';
            $sql = 'select count(A.id) from ('.$sql.') A';
        }

        $db->query($sql);
        if ($db->res){
            return array_shift($res = $db->fetch());
        }
        return false;
    }
    public function getList($data, $orderby = 'id asc', $limit = '', $offset = '')
    {
        $list  = array();
        $db    = new Model_DB();
        $where = $this->createSearchCondition($data);
        
        if(array_key_exists('site_id', $data))
            $sql = "select * from ".$this->table_name." left join D_STAFF_AUTH ON ".$this->table_name.".id = D_STAFF_AUTH.staff_id";
        else
            $sql = "select * from ".$this->table_name." ";

        $sql  .= (!empty($where) ? " where ".implode(' AND ', $where) : "") . (!empty($orderby) ? " order by {$orderby}" : "") . (!empty($limit) ? " limit {$limit}" : "") . (!empty($offset) ? " offset {$offset}" : "");
        
        $db->query($sql);
        if ($db->res){
            while($res = $db->fetch()){
                if(isset($res['id'])){
                    $list[$res['id']] = $res;
                }
                else{
                    $list[] = $res;
                }
            }
        }
        return $list;
    }

    private function createSearchCondition($data, $prefix = '')
    {
        $db    = new Model_DB();
        $where = array();
        if ($prefix != ''){
            $prefix = $prefix . '.';
        }
        $where[] = "{$prefix}enabled = 1";
        //$where[] = "{$prefix}site_id = ". $this->sys->getCurrentSiteID();//不要？

        foreach($db->getFieldList($this->table_name) as $key => $_){

            //if (isset($data[$key]) && !empty($data[$key])){//emptyは文字列の0でもtrueとなるので注意
            if (isset($data[$key]) && $data[$key] != ''){
                $value = $db->escape($data[$key]);
                if ($key == 'staff_name'){
                    $where[] = "{$prefix}{$key} collate utf8_unicode_ci like '%{$value}%'";
                }else{
                    $where[] = "{$prefix}{$key} = '{$value}'";
                }
            }
        }

        foreach($db->getFieldList('D_STAFF_AUTH') as $key => $_){
            if (isset($data[$key]) && !empty($data[$key])){
                $value = $db->escape($data[$key]);
                $where[] = "{$prefix}{$key} = '{$value}'";
            }
        }

        return $where;
    }
    
    public function validate(&$data, &$err)
    {
        $validate = new Model_Validate();
        // required
        $keys = explode(',', 'email,login_pass,staff_name');
        foreach($keys as $key){
            if (!isset($data[$key]) || $validate->NotEmpty($data[$key])){
                $err[$key] = $validate->getMessages("NotEmpty");
            }
        }
        
        //メールアドレスチェック
        $keys = explode(',', 'email');
        foreach($keys as $key){
            if ($data[$key] != '' && $validate->Email($data[$key])){
                $err[$key] = $validate->getMessages("Email");
            }
        }
        
        // メールアドレス重複チェック
        if( !isset($err['email']) ){
            $db = new Model_DB();
            if($data['id'] == ''){
                //$sql = sprintf("SELECT * FROM M_STAFF WHERE enabled = 1 AND email = '%s'", $db->quote($forms['email']));
                $count = $this->getListCount(array("email"=>$data['email']));
            }else{
                //getListCountはwhereで!=が使えないので、ここはsqlを書いている
                //$count = $this->getListCount(array("email"=>$db->escape($data['email']), "id"=>$db->escape( $data['id'] )));
                $db = new Model_DB();
                $sql = sprintf( "SELECT id FROM M_STAFF WHERE enabled = 1 AND email = '%s' AND id != %s", $db->escape( $forms['email'] ), $db->escape( $forms['id'] ));
                $db->query($sql);
                $count = $db->num_rows();
            }
            if( $count > 0 ){
                $err['email'] = $validate->getMessages("Duplicate");
            }
        }

        return empty($err);
    }
    
    //
    public function getFormKeys()
    {
        $db = new Model_DB();
        return array_keys($db->getFieldList($this->table_name));
    }
    //　状態
    public function getStatusMap()
    {
        $map    = array();
        $map[0] = '非公開';
        $map[1] = '公開';
        $map[2] = '仮登録';
        return $map;
    }
    public function getStatusName($id)
    {
        $map = $this->getStatusMap();
        return isset($map[$id]) ? $map[$id] : '';
    }
    
    //権限マスタ
    public function getAuth()
    {
        $config = __get_config('plugin.ini');
        foreach($config as $one)
        {
            $arr_auth[$one['id']] = $one['name'];
        }
        return $arr_auth;
    }
    
    public function getSiteUrl($site_id)
    {
        $site_dir = $_SESSION['DASH_BOARD']['SITE_DIR'];
        return 'http://' . $_SERVER['HTTP_HOST'] . '/' . $site_dir . '/';
    }
    public function getSiteDir($mkdir = false)
    {
        //$site_dir = 'site_'. sprintf('%04d', $site_id);
        $site_dir = $_SESSION['DASH_BOARD']['SITE_DIR'];
        if ($mkdir == true){
            chdir(SiteManageRootDir . '/htdocs/');
            if (!file_exists($site_dir)){
                mkdir($site_dir);
                chmod($site_dir, 0777);
            }
        }
        return SiteManageRootDir . '/htdocs/' . $site_dir . '/';
    }
    public function getStaffImageDir()
    {
        return SiteManageRootDir . '/htdocs/images/staff/';
    }
    public function getStaffImageUrl()
    {
        return 'http://' . $_SERVER['HTTP_HOST'] . '/images/staff/';
    }
}
?>